<?php
$notFound = false;
if (!isset($_GET['i'])) {
    $notFound = true;
}
$params = explode('|', $_GET['i']);
if (!isset($params[2])) {
    $notFound = true;
}
foreach ($params as &$param) {
    if (!is_numeric($param)) {
        $notFound = true;
    }
    $param = (int) $param;
}
if (isset($params[0]) && is_numeric($params[0])) {
    $file = dirname(__FILE__) . '/../modules/Files/uploaded/' . $params[0] .
            '.*';
    $file = glob($file);
    if (!isset($file[0])) {
        $notFound = true;
    } else {
        $file = $file[0];
    }
}

if ($notFound) {
    header('HTTP/1.0 404 not found');
    exit;
}

require dirname(__FILE__) . '/../config.php';
require dirname(__FILE__) . '/../libs/Image.php';
require dirname(__FILE__) . '/../libs/FTP.php';
$render = array(
    array('cmd' => 'import', 0 => $file),
    array('cmd' => 'resize', 0 => $params[1], 1 => $params[2], 2 =>
        isset($params[3]), 3 => -1, 4 => true)
);

$root = dirname(dirname(__FILE__));
$cache = "$root/cache/img";
$file = "$cache/simage-{$params[0]}-{$params[1]}x{$params[1]}_" .
        isset($params[3]) . ".jpg";

header('Content-Type: image/jpeg');
if (file_exists($file)) {
    echo file_get_contents($file);
}
if (is_writable($cache)) {
    Image::render($render, $file);
    echo file_get_contents($file);
} else {
    Image::import($file);
    Image::resize($params[1], $params[2], isset($params[3]));
    $out = array();
    Image::render($out, false);
}
?>
